package com.llyb.lease.web.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.llyb.lease.common.constants.RedisConstant;
import com.llyb.lease.common.exception.LeaseException;
import com.llyb.lease.common.jwt.JwtUtils;
import com.llyb.lease.common.result.ResultCodeEnum;
import com.llyb.lease.model.entity.SystemUser;
import com.llyb.lease.model.entity.UserInfo;
import com.llyb.lease.model.enums.BaseStatus;
import com.llyb.lease.web.app.service.LoginService;
import com.llyb.lease.web.app.service.UserInfoService;
import com.llyb.lease.web.app.vo.user.LoginVo;
import com.llyb.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) {
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        // 0. 限制60秒内不允许重复发送
        Boolean exist = redisTemplate.hasKey(key);

        if (exist) {
            Long expire = redisTemplate.getExpire(key,TimeUnit.SECONDS);
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            Integer appLoginCaptchaTtlSec = RedisConstant.APP_LOGIN_CAPTCHA_TTL_SEC;
            if (appLoginCodeTtlSec-expire<appLoginCaptchaTtlSec) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        /*// 1. 检查是否是新用户，新用户的话要注册
        userInfoService.*/

        // 1. 生成验证码
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        System.out.println("验证码为： " + code);

        // 2、 放入redis数据库

        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);


    }

    @Override
    public String getToken(LoginVo loginVo) {

        // 1、 校验 手机号和验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        if (code==null|| !loginVo.getCode().equals(code)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // 2、 查看用户是否存在，不存在的话注册，并且给默认值

        System.out.println(loginVo.getPhone()+ "+" + loginVo.getCode());
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo one = userInfoService.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(one)) {
            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname(loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            userInfoService.save(userInfo);
            one = userInfoService.getOne(lambdaQueryWrapper);
        }

        // 3、 用户是否可用
        if (one.getStatus()== BaseStatus.DISABLE) {
            throw  new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        // 4、 放回token
        return JwtUtils.createToken(one.getId(),one.getPhone());
    }

    @Override
    public UserInfoVo info(String token) {
        Integer userId = (Integer) JwtUtils.parseToken(token).get("userId");

        UserInfo userInfo = userInfoService.getById(userId);

        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
